const { Member, Manager } = require('../models');
const { v4: uuidv4 } = require('uuid');

// 微信登录
exports.wechatLogin = async (req, res) => {
  try {
    const { code, userInfo } = req.body;
    
    // 检查用户是否已存在
    const existingMember = await Member.findOne({
      where: { student_id: userInfo.studentId },
      include: [{
        model: Manager,
        required: false
      }]
    });

    if (existingMember) {
      // 用户已存在，返回用户信息
      return res.json({
        success: true,
        data: {
          userId: existingMember.user_id,
          isManager: !!existingMember.manager,
          managerId: existingMember.manager?.manager_id
        }
      });
    }

    // 用户不存在，返回需要注册的标识
    return res.json({
      success: true,
      needRegister: true
    });

  } catch (error) {
    console.error('微信登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后重试'
    });
  }
};

// 用户注册
exports.register = async (req, res) => {
  try {
    const { userName, studentId, managerId } = req.body;

    // 检查学号是否已被注册
    const existingMember = await Member.findOne({
      where: { student_id: studentId }
    });

    if (existingMember) {
      return res.status(400).json({
        success: false,
        message: '该学号已被注册'
      });
    }

    // 检查managerId是否存在
    const manager = await Manager.findByPk(managerId);
    if (!manager) {
      return res.status(400).json({
        success: false,
        message: '无效的负责人编号'
      });
    }

    // 创建新用户
    const newMember = await Member.create({
      user_id: uuidv4(),
      user_name: userName,
      student_id: studentId,
      manager_id: managerId
    });

    res.json({
      success: true,
      data: {
        userId: newMember.user_id,
        isManager: false
      }
    });

  } catch (error) {
    console.error('用户注册失败:', error);
    res.status(500).json({
      success: false,
      message: '注册失败，请稍后重试'
    });
  }
};

// 注册为负责人
exports.registerAsManager = async (req, res) => {
  try {
    const { userId, contactInfo } = req.body;

    // 检查用户是否存在
    const member = await Member.findByPk(userId);
    if (!member) {
      return res.status(400).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 检查用户是否已经是负责人
    const existingManager = await Manager.findOne({
      where: { user_id: userId }
    });

    if (existingManager) {
      return res.status(400).json({
        success: false,
        message: '该用户已经是负责人'
      });
    }

    // 创建新负责人
    const newManager = await Manager.create({
      manager_id: uuidv4(),
      contact_info: contactInfo,
      user_id: userId
    });

    // 更新用户的manager_id
    await Member.update(
      { manager_id: newManager.manager_id },
      { where: { user_id: userId } }
    );

    res.json({
      success: true,
      data: {
        managerId: newManager.manager_id
      }
    });

  } catch (error) {
    console.error('注册负责人失败:', error);
    res.status(500).json({
      success: false,
      message: '注册失败，请稍后重试'
    });
  }
}; 